package com.megvii.koala.tv.web;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Created by linyue on 16/1/24.
 */
public class KoalaTvWebView extends WebView implements KoalaTvWebAPI
{
    private KoalaTvWebViewListener listener;

    private Handler handler;

    public KoalaTvWebView(Context context)
    {
        super(context);
        init();
    }

    public KoalaTvWebView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }

    public KoalaTvWebView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init();
    }

    private void init()
    {
        if (!isInEditMode())
        {
            handler = new Handler(Looper.getMainLooper());
            setBackgroundColor(0x00000000);
            getSettings().setJavaScriptEnabled(true);
            getSettings().setDomStorageEnabled(true);
            getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // 设置
            // 缓存模式
            setWebContentsDebuggingEnabled(true);
            // webView.getSettings().setBuiltInZoomControls(true);
            setFocusable(false);
            setClickable(false);
            // 支持中文，否则页面中中文显示乱码
            // webView.getSettings().setDefaultTextEncodingName("GBK");
            // 限制在WebView中打开网页，而不用默认浏览器
            setWebViewClient(new KoalaTVWebViewClient());
            setWebChromeClient(new KoalaTVWebChromeClient());
            addJavascriptInterface(new WebCallback(), "KCAndroid");
            requestFocus();
        }
    }

    /**
     * 抓拍上传
     */
    public void KCUpload()
    {
        evaluateJavascript("KCScreen.autoregister()", null);
    }

    /**
     * 更换主题
     */
    public void KCTheme(String theme)
    {
        evaluateJavascript("KCScreen.theme('" + theme + "')", null);
    }

    /**
     * 发现本地盒子回传token
     * 1,token
     */
    public void KCDiscovery(String boxToken, String boxAddress, String deviceToken)
    {
        evaluateJavascript(
                "KCScreen.discover('" + boxToken + "', '" + boxAddress + "', '" + deviceToken + "')",
                null);
    }

    public void setListener(KoalaTvWebViewListener listener)
    {
        this.listener = listener;
    }

    public interface KoalaTvWebViewListener
    {
        public void onPageStartLoading(String url);

        public void onPageFinished(String url);

        public void onPageError(int errorCode, String description, String failingUrl);

        public void onProgressChanged(int newProgress);

        public void onPlayVideo(final String src, final float left, final float top,
                final float width, final float height);

        public void onPlayLocalVideo(final float left, final float top, final float width,
                final float height);

        public void onOpenDoor();
    }

    class KoalaTVWebViewClient extends WebViewClient
    {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description,
                String failingUrl)
        {
            if (listener != null)
            {
                listener.onPageError(errorCode, description, failingUrl);
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon)
        {
            if (listener != null)
            {
                listener.onPageStartLoading(url);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url)
        {
            if (listener != null)
            {
                listener.onPageFinished(url);
            }
        }
    }

    class KoalaTVWebChromeClient extends WebChromeClient
    {
        public void onProgressChanged(WebView view, int newProgress)
        {
            if (listener != null)
            {
                listener.onProgressChanged(newProgress);
            }
        }
    }

    class WebCallback
    {
        /**
         * 视频的位置
         */
        @JavascriptInterface
        public void playLocalVideo(final float left, final float top, final float width,
                final float height)
        {
            handler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    if (listener != null)
                    {
                        listener.onPlayLocalVideo(left, top, width, height);
                    }
                }
            });
        }

        @JavascriptInterface
        public void playVideo(final String src, final float left, final float top,
                final float width, final float height)
        {
            handler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    if (listener != null)
                    {
                        listener.onPlayVideo(src, left, top, width, height);
                    }
                }
            });
        }

        /**
         * 开门 这个必须写，不写的话Javascript不会调用
         */
        @JavascriptInterface
        public void openDoor()
        {
            handler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    if (listener != null)
                    {
                        listener.onOpenDoor();
                    }
                }
            });
        }
    }
}
